Chart for WinRT > Chart Features > Data Binding > Data Binding in Markup |
Binding data in XAML markup is a simple matter of setting a few properties. In the example that follows, three key properties, ItemsSource, ValueBinding, and XValueBinding are set with Binding parameters:
XAML Markup |
Copy Code
|
---|---|
<Chart:C1Chart x:Name="c1Chart1" Height="350" Width="450" ChartType="Column" Grid.Row="1" Palette="Solstice" > <Chart:C1Chart.View> <Chart:ChartView > <Chart:ChartView.AxisX> <Chart:Axis IsTime="True" AnnoFormat="MM-dd" /> </Chart:ChartView.AxisX> </Chart:ChartView> </Chart:C1Chart.View> <Chart:C1Chart.Data> <Chart:ChartData ItemsSource="{Binding Items}"> <Chart:ChartData.Children> <Chart:XYDataSeries ValueBinding="{Binding Volume}" XValueBinding="{Binding Date}" /> </Chart:ChartData.Children> </Chart:ChartData> </Chart:C1Chart.Data> </Chart:C1Chart> |
The ItemsSource property is the most important one to set. This property binds the Chart's Data property to a collection called Items. The Values that are bound in the XYDataSeries are from the Items collection. By setting three properties, you can very easily populate your chart with data, instead of having to create the data declaratively.
For reference, the data used in this topic is random data. The Items collection is within a MainViewModel class. It is set as the DataContext object within the MainPage() constructor. Setting the DataContext allows you to share the data across multiple controls:
C# |
Copy Code
|
---|---|
public MainPage() { this.InitializeComponent(); this.DataContext = new MainViewModel(); } public class MainViewModel { public ObservableCollection<DataItem> Items { get; private set; } public MainViewModel() { Random rnd = new Random(); this.Items = new ObservableCollection<DataItem>(); for (int i = 0; i < 10; i++) { this.Items.Add(new DataItem() { Volume = rnd.Next(100), Date = DateTime.Now.AddDays(i) }); } } } public class DataItem { public DateTime Date { get; set; } public double Volume { get; set; } } } } |